<template>
  <div class="in-using-container">
    
    <!-- 主交互区域 -->
    <div class="main-interactive">
      <div class="monitor-title">用电监控</div>
      <div class="reminder-banner">
        温馨提示: 安全第一, 小心用电!
      </div>
      
      <div class="electricity-status">
        <div class="status-circle">
          <i class="plug-icon">⚡</i>
        </div>
        <div class="recharge-info">
          <span class="recharge-label">充值金额</span>
          <span class="recharge-amount">{{ rechargeAmount }}元</span>
          <button class="renew-button" @click="renewRecharge">续费</button>
        </div>
      </div>
    </div>

    <!-- 信息网格 -->
    <div class="info-grid">
      <div class="info-card">
        <i class="card-icon start-icon">▶</i>
        <div class="card-content">
          <div class="card-value">{{ record.createdAt }}</div>
          <div class="card-label">开始时间</div>
        </div>
      </div>
      
      <div class="info-card">
        <i class="card-icon duration-icon">⏰</i>
        <div class="card-content">
          <div class="card-value">{{ record.useTime }}分钟</div>
          <div class="card-label">用电时长</div>
        </div>
      </div>
      
      <div class="info-card">
        <i class="card-icon consumed-icon">¥</i>
        <div class="card-content">
          <div class="card-value">{{ record.cost }}元</div>
          <div class="card-label">已消费</div>
        </div>
      </div>
      
      <div class="info-card">
        <i class="card-icon usage-icon">📈</i>
        <div class="card-content">
          <div class="card-value">{{ record.energy }}度</div>
          <div class="card-label">已用电</div>
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <div class="button-row">
        <button class="action-btn continue-btn" @click="continueUsage">
          继续用电
        </button>
        <button class="action-btn pause-btn" @click="pauseUsage">
          暂停用电
        </button>
      </div>
      <button class="end-button" @click="endUsage">
        结束用电
      </button>
    </div>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import { getRecord, addRecord, finishRecord } from '@/api/business/record'
import { setPwrSta } from '@/api/device/iot'
import { listRecharge } from '@/api/business/recharge'

export default {
  name: 'InUsing',
  data() {
    return {
      currentTime: '',
      startTime: '',
      usageDuration: '0 分钟',
      consumedAmount: '0.00',
      electricityUsed: '0.00',
      rechargeAmount: '0.00',
      startTimestamp: null,
      durationTimer: null,
      isPaused: false,
      record: null
    }
  },
  mounted() {
    this.rechargeAmount = window.amount
    this.initTime()
    this.startDurationTimer()
    if (window.record == null) {
      this.createRecord()
    } else {
      this.record = window.record
      const query = {
        userId: window.userInfo.userId,
        status: 1
      }
      listRecharge(query).then(response => {
        window.orderId = response.rows[0].orderId
        window.amount = response.rows[0].amount
        this.rechargeAmount = response.rows[0].amount
      })
    }
  },
  beforeDestroy() {
    if (this.durationTimer) {
      clearInterval(this.durationTimer)
    }
  },
  methods: {
    createRecord() {
      const record = {
        userId: window.userInfo.userId,
        meterId: window.meterId,
        orderId: window.orderId,
        energy: 0,
        cost: 0,
        status: 1,
        useTime: 0
      }
      addRecord(record).then(response => {
        this.record = response.data
      })
    },
    getRecord() {
      getRecord(this.record.id).then(response => {
        this.record = response.data
        // TODO：余额用完
      })
    },
    initTime() {
      const now = new Date()
      this.currentTime = now.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      })
      this.startTime = this.currentTime
      this.startTimestamp = now.getTime()
      
      // 更新时间
      setInterval(() => {
        this.currentTime = new Date().toLocaleTimeString('zh-CN', { 
          hour: '2-digit', 
          minute: '2-digit' 
        })
        this.getRecord()
      }, 10000)
    },
    startDurationTimer() {
      this.durationTimer = setInterval(() => {
        if (!this.isPaused) {
          const now = new Date().getTime()
          const diff = now - this.startTimestamp
          const minutes = Math.floor(diff / 60000)
          const seconds = Math.floor((diff % 60000) / 1000)
          
          if (minutes > 0) {
            this.usageDuration = `${minutes} 分钟 ${seconds} 秒`
          } else {
            this.usageDuration = `${seconds} 秒`
          }
        }
      }, 10000) // 每10秒更新一次
    },
    continueUsage() {
      this.isPaused = false
      this.$message.success('继续用电')
      // 发送开启电源
      setPwrSta(window.imei, 1)
      .then(response => {
        this.$message.success('发送启动用电指令成功')
      })
    },
    pauseUsage() {
      this.isPaused = true
      this.$message.info('已暂停用电')
      // 发送关闭电源
      setPwrSta(window.imei, 0)
      .then(response => {
        this.$message.success('发送暂停用电指令成功')
      })
    },
    endUsage() {
      this.$confirm('确定要结束用电吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.success('用电已结束')
        this.record.status = 0
        this.record.finishedTime = new Date()
        finishRecord(this.record.id).then(response => {
          window.record = response.data
          this.$router.push('/wechat/finish')
        })
      }).catch(() => {
        // 用户取消
      })
    },
    renewRecharge() {
      this.$message.info('跳转到续费页面')
      // TODO：跳转到续费页面
    }
  }
}
</script>

<style scoped>
.in-using-container {
  min-height: 100vh;
  background: #f5f5f5;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 统一取消 i 标签和图标类的斜体样式 */
.in-using-container i,
.card-icon,
.nav-arrow,
.plug-icon,
.indicator-arrow,
.nav-icon,
.close-icon,
.more-icon {
  font-style: normal;
}

/* 状态栏样式 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  background: #000;
  color: white;
  font-size: 14px;
  font-weight: 600;
}

.status-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.signal-bars {
  display: flex;
  gap: 2px;
}

.bar {
  width: 3px;
  height: 6px;
  background: white;
  border-radius: 1px;
}

.battery {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 头部样式 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: white;
  border-bottom: 1px solid #f0f0f0;
}

.title-center {
  text-align: center;
}

.main-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 4px;
  color: #333;
}

.sub-title {
  font-size: 12px;
  color: #999;
}

.close-icon, .more-icon {
  font-size: 20px;
  cursor: pointer;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
}

/* 主交互区域样式 */
.main-interactive {
  background: #1890ff;
  padding: 20px;
  color: white;
  position: relative;
}

.nav-arrow {
  position: absolute;
  left: 20px;
  top: 20px;
  font-size: 20px;
  cursor: pointer;
}

.monitor-title {
  text-align: center;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 16px;
}

.reminder-banner {
  background: rgba(255, 255, 255, 0.2);
  padding: 8px 16px;
  border-radius: 20px;
  text-align: center;
  font-size: 14px;
  margin-bottom: 24px;
}

.electricity-status {
  text-align: center;
}

.status-circle {
  width: 80px;
  height: 80px;
  border: 3px solid #52c41a;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 16px;
  background: rgba(255, 255, 255, 0.1);
}

.plug-icon {
  font-size: 32px;
  color: #52c41a;
}

.recharge-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  flex-wrap: wrap;
}

.recharge-label {
  font-size: 14px;
}

.recharge-amount {
  font-size: 16px;
  font-weight: 600;
}

.renew-button {
  background: rgba(255, 255, 255, 0.3);
  color: white;
  border: none;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  cursor: pointer;
}

.renew-button:hover {
  background: rgba(255, 255, 255, 0.4);
}

/* 信息网格样式 */
.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  padding: 16px;
  background: white;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.info-card {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  gap: 12px;
}

.card-icon {
  font-size: 24px;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  line-height: 40px; /* 确保文本垂直居中（双保险） */
  text-align: center; /* 文本水平居中（双保险） */
}

.start-icon {
  background: #52c41a;
  color: white;
}

.duration-icon {
  background: #fa8c16;
  color: white;
}

.consumed-icon {
  background: #f5222d;
  color: white;
}

.usage-icon {
  background: #1890ff;
  color: white;
}

.card-content {
  flex: 1;
}

.card-value {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.card-label {
  font-size: 12px;
  color: #666;
}

/* 操作按钮样式 */
.action-buttons {
  padding: 16px;
  background: white;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.button-row {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.action-btn {
  flex: 1;
  background: white;
  color: #1890ff;
  border: 1px solid #1890ff;
  padding: 12px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.action-btn:hover {
  background: #f0f8ff;
}

.end-button {
  width: 100%;
  background: #1890ff;
  color: white;
  border: none;
  padding: 16px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: background-color 0.3s;
}

.end-button:hover {
  background: #40a9ff;
}

.end-button:active {
  background: #096dd9;
}

/* 底部导航样式 */
.bottom-nav {
  display: flex;
  justify-content: space-around;
  padding: 12px 0;
  background: white;
  border-top: 1px solid #f0f0f0;
  position: fixed;
  bottom: 20px;
  left: 0;
  right: 0;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  padding: 8px;
  border-radius: 8px;
  transition: all 0.3s;
}

.nav-item.active {
  background: #e6f7ff;
}

.nav-icon {
  font-size: 20px;
}

.nav-item.active .nav-icon {
  background: #1890ff;
  color: white;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-text {
  font-size: 12px;
  color: #666;
}

.nav-item.active .nav-text {
  color: #1890ff;
  font-weight: 600;
}

/* 底部指示器样式 */
.bottom-indicator {
  position: fixed;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  padding: 8px;
}

.indicator-arrow {
  font-size: 16px;
  color: #999;
}

.indicator-line {
  width: 40px;
  height: 4px;
  background: #ddd;
  border-radius: 2px;
}

/* 响应式设计 */
@media (max-width: 375px) {
  .info-grid {
    margin: 12px;
    padding: 12px;
  }
  
  .action-buttons {
    margin: 12px;
    padding: 12px;
  }
  
  .status-circle {
    width: 60px;
    height: 60px;
  }
  
  .plug-icon {
    font-size: 24px;
  }
}

/* 图标样式 */
.wifi-icon::before {
  content: "📶";
}

.battery-icon::before {
  content: "🔋";
}
</style>
